package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Gathering;
import cn.wolfcode.crm.domain.PotentialStudent;
import cn.wolfcode.crm.mapper.GatheringMapper;
import cn.wolfcode.crm.query.GatheringQueryObject;
import cn.wolfcode.crm.service.IGatheringService;
import cn.wolfcode.crm.service.IPotentialStudentService;
import cn.wolfcode.crm.util.PageResult;
import cn.wolfcode.crm.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class GatheringServiceImpl implements IGatheringService {
    @Autowired
    private GatheringMapper gatheringMapper;
    @Autowired
    private IPotentialStudentService potentialStudentService;


    @Override
    public PageResult getAll(GatheringQueryObject qo) {
        int count = gatheringMapper.queryCount(qo);
        if (count == 0) {
            return new PageResult(0, Collections.EMPTY_LIST);
        }
        List<Gathering> data = gatheringMapper.queryList(qo);
        return new PageResult(count, data);
    }

    @Override
    public void saveOrUpdate(Gathering gathering) {
        Long studentId = gathering.getStudent().getId();
        PotentialStudent ps = potentialStudentService.selectByPrimaryKey(studentId);
        gathering.setStudent(ps);
        if (gathering.getId() != null) {
           gatheringMapper.updateByPrimaryKey(gathering);
        }else {
            gathering.setTime(new Date());
            gatheringMapper.insert(gathering);
        }
    }

    @Override
    public void audit(Long id) {
        Gathering gathering = gatheringMapper.selectByPrimaryKey(id);
        if (!gathering.isState()) {
            Employee employee = UserContext.getUserContext();
            gathering.setAuditorMan(employee);
            gathering.setState(true);
            gatheringMapper.audit(gathering);
        }else {
            throw new RuntimeException("已经审核!!!!");
        }
    }

    @Override
    public void delete(Long id) {
        if (id != null) {
            gatheringMapper.deleteByPrimaryKey(id);
        }else {
            throw new RuntimeException("数据异常");
        }
    }
}
